let machine = require('../public/index.js');
const { HotpotOrder, HotpotInFoodOrder, HotpotOutFoodOrder, HotpotPreFurnaceOrder, HotpotDeviceStatus, HotpotInfo } = require('../db/schema')
const { fnGetStatus, fnGetDeviceStatusObj, fnGetNewDevicesStatus, fnCheckData, fnGetFurnaceStatus } = require('./utis')
const { to, reverseTcpData, jsonCopy } = require('../utils/index')
const date = require('silly-datetime')
const { reqchangeFreezerStock, reqchangeThermotankStock, reqcheckQrCode, reqgetThermotankTakePlace, reqgetThermotankGivePlace, requpdateProductStatus, reqresponseInstructionResult, reqgetStores, reqgetDevices, reqgetProducts, reqgetAccessToken, reqcallTakeFood } = require('./request')
const config = require('../config/index.js');
const kafka = require('../utils/kafka-utils');

let EventEmitter = require('events').EventEmitter;
let event = new EventEmitter();

let today = date.format(new Date(), 'YYYYMMDD');

class hotPotRice extends machine {
    constructor(http, tcpServe) {
        super(http, tcpServe);
        this.access_token = ''
        this.storeId = ''
        this.deviceId = ''
        this.productId1 = '' 
        this.productId2 = '' 

        this.devices = {}
        this.furnace1 = {}
        this.furnace2 = {}

        this.random = 1001

        this.machineInfos = [
            { header: '170', ip: '::ffff:192.168.3.200' }
        ]

        this.startOrderSwitch = true

        

        this.resendObj = {}

        this.prepareSort = 1

        this.kafkaLock = false
        this.sendLock = false
        this.freezerLock = false
        this.freezerTimer = null
        //复位
        this.restoration()
        //获取门店信息
        this.getStoreInfo()
        
        let timer = setInterval(() => {
            if(!this.storeId || !this.deviceId || !this.productId1 || !this.productId2 ){
                console.log('开始初始化', date.format(new Date(), 'YYYY-MM-DDThh:mm:ss'))
                this.getStoreInfo()
            }else{
                console.log('初始化门店/设备/菜品信息成功', date.format(new Date(), 'YYYY-MM-DDThh:mm:ss'))
                this.sendCall()
                this.resetInfo()
                clearInterval(timer)
            }
        }, 5000)
        this.init()

        this.callTimer = 10
        this.forceLock = false

        setInterval(() => {
            this.sendLock = false
        }, 2000)
        
        

    }

    //发送重置叫号
    sendCall(){
        setTimeout(async () => {
            let [err, res] = await to(reqcallTakeFood({storeId: this.storeId, deviceId: this.deviceId, access_token: this.access_token}))
            if(err) return
            if (res.statusCode !== '200') return console.log(res.statusMsg)
            console.log('重置叫号成功')
            this.sendCall()
        }, this.callTimer * 1000)
        
    }
    //复位
    restoration(){
        // HotpotOrder.
    }

    //重置信息
    resetInfo(){
        console.log('重置信息开启')
        setInterval(async () => {
            let[error, result] = await to(HotpotInfo.findOne())
            if(error) return console.log('查找重置信息出错')
            let {callTimer, forceLock, forceOrder, send} = result
            this.callTimer = callTimer * 1
            this.forceLock = forceLock === 2
            if(this.forceLock && send === 2){
                let machine = this.machineInfos.find(item => item.header === '170')
                
                this.forceSend(this.clients[machine.ip], forceOrder)
            }
        }, 2000)
    }

    forceSend(socket, content){
        let { freezerStatus, thermotank1Status, thermotank2Status, inport1Status, inport2Status, outport1Status, outport2Status } = fnGetDeviceStatusObj(this.devices['170'])
        let arr = content.split(',')
        arr = arr.map(item => item * 1)
        if(arr[5] === 1){
            if(!thermotank1Status) return console.log('强制下单失败,1号保温柜忙碌')
        }
        if(arr[5] === 2){
            if(!thermotank2Status) return console.log('强制下单失败,2号保温柜忙碌')
        }
        socket.write(this.messageResponse(...arr), 'hex')
        console.log('强制下发命令', this.messageResponse(...arr))
        HotpotInfo.updateOne({send: 2}, {send: 1, forceLock: 1}, async (error, result) => {
            if(error) return console.log('下发任务,修改数据库状态失败')
            console.log('下发任务,修改数据库状态成功')
            let [err, res] = await to(reqchangeThermotankStock({ storeId: this.storeId, deviceId: this.deviceId, thermotankNo: arr[5], placeNo: arr[6], placeStock: 0, access_token: this.access_token }))
            console.log(err, res)
            console.log('修改云端减少库存成功,', arr[5], arr[6])
        })
    }

    

    getStoreInfo(_id){
        reqgetAccessToken().then(res => {
            if(res.statusCode !== '000000') return console.log(res.statusMsg)
            this.access_token = res.data.access_token
            console.log('获取token成功')
            return HotpotInfo.findOne()
        }).then(result => {
            if(!result) return console.log('初始化信息出错')
            let {storeId} = result
            this.storeId = storeId
            console.log('读取门店信息成功id', this.storeId)
            return reqgetDevices({storeId, access_token: this.access_token})
        }).then(res => {
            if(res.statusCode !== '200') return console.log(res.statusMsg, 2)
            this.deviceId = res.data[0].id
            console.log('获取设备信息成功', this.deviceId)
            return reqgetProducts({deviceId: this.deviceId, access_token: this.access_token})
        }).then(res => {
            if(res.statusCode !== '200') return console.log(res.statusMsg, 1)
            this.productId1 = res.data[0].id
            this.productId2 = res.data[1].id
            console.log('获取菜品信息成功', this.productId1, res.data[0].name, this.productId2, res.data[1].name)
        }).catch(err => {
            console.log(err)
        })
    }

    init() {
        console.log('初始化成功')
        this.listenKafka()
        this.listenTcpData()
        // this.checkHeartbeat()
        setInterval(() => {
            this.getDeviceStatus(true)
            this.getFurnaceOrder()
        }, 5000)

    }

    listenKafka() {
        let kafkaClient = new kafka(config.kafkaUrl(), [{ topic: 'claypot_instruction_1213665451765596162' }]);
        kafkaClient.message((message) => {
            console.log(message)
            let random = Math.floor(Math.random() * (1000 - 1 + 1)) + 1 * 3
            setTimeout(async () => {
                let value = JSON.parse(message.value)
                //备餐命令
                if (value.instruction === 'COOK_CLAYPOT') {
                    clearTimeout(this.freezerTimer)
                    this.freezerLock = true
                    this.freezerTimer = setTimeout(() => {
                        this.freezerLock = false
                    }, 60 * 1000)
                    this.insertOrder(value)
                    let [err, res] = await to(reqresponseInstructionResult({ targetId: value.id, status: 101, message: '已收到', access_token: this.access_token }))
                    console.log('reqresponseInstructionResult', err, res)
                    if (err) return
                    if (res.statusCode !== '200') return console.log(res.statusMsg)
                    console.log('收到备餐命令,回应云端成功')
                    //打烊清库存
                } else if (value.instruction === 'CLEAR_THERMOTANK_STOCK') {
                    this.insertOutFoodOrder(value, 1)
                    let [err, res] = await to(reqresponseInstructionResult({ targetId: value.id, status: 101, message: '已收到', access_token: this.access_token }))
                    console.log('reqresponseInstructionResult', err, res)
                    if (err) return
                    if (res.statusCode !== '200') return console.log(res.statusMsg)
                    console.log('收到打烊命令,回应云端成功')
                    //超时清库存
                } else if (value.instruction === 'CLEAR_OVERTIME_PRODUCT') {
                    this.insertOutFoodOrder(value, 2)
                    let [err, res] = await to(reqresponseInstructionResult({ targetId: value.id, status: 101, message: '已收到', access_token: this.access_token }))
                    console.log('reqresponseInstructionResult', err, res)
                    if (err) return
                    if (res.statusCode !== '200') return console.log(res.statusMsg)
                    console.log('收到清理库存命令,回应云端成功')
                }
            }, random)

        })
    }

    //插入备餐数据
    async insertOrder(order) {
        let insertData = []

        let preFurnaceQuantity1 = 0
        let preFurnaceQuantity2 = 0

        order.data.forEach(item => {
            let orderDetail = jsonCopy(item)
            // 统计要预热的炉头
            if (item.productCode === 1) { preFurnaceQuantity1 += item.quantity }
            if (item.productCode === 2) { preFurnaceQuantity2 += item.quantity }
            orderDetail.quantity = 1
            for (let i = 0; i < item.quantity; i++) {
                insertData.push({
                    date: today,
                    orderDetail,
                    status: 0
                })
            }

        })

        let [error1, result1] = await to(HotpotOrder.insertMany(insertData))
        if (error1) return

        console.log("insert last mealId = " + (result1[result1.length - 1]._mealId - 1))

        //接收到订单数据之后预热炉头1
        if (preFurnaceQuantity1) {
            this.insertPreFurnaceOrder(preFurnaceQuantity1, 1)
        }

        //接收到订单数据之后预热炉头2
        if (preFurnaceQuantity2) {
            this.insertPreFurnaceOrder(preFurnaceQuantity2, 2)
        }

    }

    //插入预热炉头数据
    async insertPreFurnaceOrder(quantity, furnaceId) {
        let insertData = [{
            date: today,
            quantity,
            furnaceId,
            status: 0,
        }]
        let [error, result] = await to(HotpotPreFurnaceOrder.insertMany(insertData))
        if (error) return
        let _preFurnaceOrderId = result[0]._preFurnaceOrderId
        console.log("insert last _preFurnaceOrderId = " + _preFurnaceOrderId)
    }

    //插入打烊和超时数据(出餐数据)
    async insertOutFoodOrder(order, type) {
        let insertData = []
        let data = order.data.thermotankPlaces
        data.forEach(item => {
            item.places.forEach(subItem => {
                insertData.push({
                    date: today,
                    orderDetail: {
                        thermotankNo: item.thermotank,
                        placeNo: subItem
                    },
                    position: item.thermotank,
                    type,
                    status: 0
                })
            })
        })

        let [error, result] = await to(HotpotOutFoodOrder.insertMany(insertData))
        if (error) return
        console.log('insert last _outFoodOrderId = ' + result[result.length - 1]._outFoodOrderId)
        this.clearFood(type, 1)
        setTimeout(() => {
            this.clearFood(type, 2)
        }, 1000)
    }

    clearFood(type, position) {
        let timer = setInterval(async () => {
            let [error, result] = await to(HotpotOutFoodOrder.findOne({ $and: [{ $or: [{ status: 0 }, { status: 3 }] }, { date: today, type, position }] }))
            if (error) return console.log('清理库存有误')
            if (!result) {
                console.log('清理库存完毕,type:', type)
                clearInterval(timer)
            } else {
                let { freezerStatus, thermotank1Status, thermotank2Status, inport1Status, inport2Status, outport1Status, outport2Status } = fnGetDeviceStatusObj(this.devices['170'])
                if (result.position === 1) {
                    if (thermotank1Status) {
                        let machine = this.machineInfos.find(item => item.header === '170')
                        this.outFood(machine.ip, result)
                    }
                }

                if (result.position === 2) {
                    if (thermotank2Status) {
                        let machine = this.machineInfos.find(item => item.header === '170')
                        this.outFood(machine.ip, result)
                    }
                }

            }
        }, 10000)

    }

    listenTcpData() {
        this.tcpConnect(socket => {
            this.clientConnected(socket);
            this.addSocket(socket)
        })
    }

    receive(key, arr, type) {
        console.log('客户端响应', arr.toString(), date.format(new Date(), 'YYYY-MM-DDThh:mm:ss'))
        this.sendLock = false
        let result = fnCheckData(arr)
        if (result.code !== 0) return console.log(result.msg)
        // 客户端 1心跳 2设备异常状态上报 3设备状态上报 4是否备餐响应 5备餐完成 6是否可以出餐响应 7上报出餐结果 8是否可以放餐响应 9上报放餐结果 10炉头状态上报 11响应预热炉头 12炉头预热结果
        // 服务端 1响应心跳 2响应异常状态上报 3响应状态上报 4发起备餐 5响应备餐完成 6发起出餐 7响应出餐结果 8发起放餐 9响应放餐结果 10响应炉头状态上报 11发起预热炉头 12响应炉头预热结果

        if (this['command' + type]) {
            this.clients[key].send = (arr) => {
                this.clients[key].write(this.messageResponse(...arr), 'hex')
            }
            this['command' + type](this.clients[key], arr, this.devices)
        } else {
            let emitArr = [4, 6, 8, 11]
            if (emitArr.includes(type)) {
                if (!(event.eventNames().includes(arr[2] + ''))) return console.log('客户端响应了未下发的命令', arr.toString())
                event.emit(arr[2], key, arr, type);
            } else {
                //发送未定义消息类型
                console.log('未定义消息类型')
            }
        }

    }

    //用户扫码
    async receiveScanData(qrCode, key) {
        if(this.forceLock) return console.log('强制停止状态中,扫码无效')
        qrCode = qrCode.replace('\r', '')
        qrCode = qrCode.replace('\\000026', '')
        let exitNo = key === this.scanIp.intake1 ? 1 : 2
        let { freezerStatus, thermotank1Status, thermotank2Status, inport1Status, inport2Status, outport1Status, outport2Status } = fnGetDeviceStatusObj(this.devices['170'])
        if (exitNo === 1 && !thermotank1Status) return console.log('1号保温柜忙碌中, 不能出餐')
        if (exitNo === 2 && !thermotank2Status) return console.log('2号保温柜忙碌中, 不能出餐')

        console.log({ storeId: this.storeId, deviceId: this.deviceId, qrCode, exitNo })
        let [err, res] = await to(reqcheckQrCode({ storeId: this.storeId, deviceId: this.deviceId, qrCode, exitNo, access_token: this.access_token }))
        console.log(err, res)
        if (err) return
        if (res.statusCode !== '200') return console.log(res.statusMsg)
        if (res.data.valid !== 'Y') return console.log(res.data.tip)  //Y可出餐,N不可出餐

        let [err1, res1] = await to(reqgetThermotankTakePlace({ storeId: this.storeId, deviceId: this.deviceId, productId: res.data.productId, access_token: this.access_token }))
        console.log(err1, res1)
        if (err1) return
        if (res1.statusCode !== '200') return console.log(res1.statusMsg)
        let orderDetail = res1.data
        let insertData = [{
            date: today,
            status: 0,
            position: exitNo,
            type: 0,
            orderDetail,
            orderDetailId: res.data.orderDetailId
        }]
        let [error, result] = await to(HotpotOutFoodOrder.insertMany(insertData))
        if (error) return
        console.log('插入用户扫码出餐任务', result[0]._id)
        let machine = this.machineInfos.find(item => item.header === '170')
        this.outFood(machine.ip, result[0])
        // let { _outFoodOrderId } = result[0]
        // console.log("insert last _outFoodOrderId = " + _outFoodOrderId)
        // let content = this.messageResponse(170, 4, this.random, 6, orderDetail.productCode, orderDetail.deviceLevel, orderDetail.productCode)
        // this.outFood(key, res1.data)
    }

    addSocket(socket) {
        this.machineInfos.forEach(machine => {
            if (machine.ip === socket.remoteAddress) {
                socket.lastTime = new Date().getTime()
                let key = socket.remoteAddress
                this.clients[key] && this.clearSocket(key)
                this.clients[key] = socket
                // this.devices[key] = { status: 0 } //0未发送状态 1已发送状态
                // this.thermotanks[key] = { status: 0 } //0未发送状态 1已发送状态
                console.log(key + ' 煲仔饭设备已连接')
            }
        })
    }

    clearSocket(key) {
        this.clients[key].destroy();
        delete this.clients[key];
        delete this.devices[key];
        delete this.thermotanks[key];
    }

    checkHeartbeat() {
        setInterval(() => {
            let now = new Date().getTime();
            for (let key in this.clients) {
                if (now - this.clients[key].lastTime > 12000) {
                    this.clearSocket(key)
                    console.log(key + ' 超时下线')
                }
            }
        }, 12000 * 1000);
    }

    send(socket, content, cb) {
        
        if (!socket) return
        if (this.sendLock) return
        if(this.forceLock) return console.log('强制停止状态中,不能下发')
        let random = this.random
        event.once(random, cb)
        this.random++
        if (this.random > 65535) this.random = 1001
        console.log('下发', content, date.format(new Date(), 'YYYY-MM-DDThh:mm:ss'))
        this.sendLock = true
        socket.write(content, 'hex')
        // this.resendObj[random] = 1
        // this.resend(random, socket, content, cb)
    }

    resend(random, socket, content, cb) {
        setTimeout(() => {
            if (event.eventNames().includes(random + '')) {
                if (this.resendObj[random] < 3) {
                    this.resendObj[random] += 1
                    socket.write(content, 'hex')
                    this.resend(random, socket, content, cb)
                } else {
                    event.removeListener(random, cb)
                    delete this.resendObj[random]
                    console.log('命令超时未回复', content)
                }
            }
        }, 3000)
    }

    responseMsg(arr) {
        return [arr[0], arr[1], arr[2], 0]
    }

    //下发备餐
    prepareFood(key, order) {
        const { _id, orderDetail } = order
        let content = this.messageResponse(170, 4, this.random, 6, order._mealId, orderDetail.productCode, orderDetail.deviceLevel, orderDetail.productCode)
        console.log('下发备餐', content, date.format(new Date(), 'YYYY-MM-DDThh:mm:ss'))
        this.send(this.clients[key], content, (key1, arr, type) => {
            HotpotOrder.updateOne({ _id }, { status: arr[4] }, (error, result1) => {
                if (error) return
                switch (arr[4]) {
                    case 1: console.log('更新成功, _id: ' + _id); break;
                    case 2: console.log('执行失败，正在备餐中或者冷柜无库存, _id: ' + _id); break;
                    case 3: console.log('备餐忙碌中，稍后重试, _id: ' + _id); break;
                    default: console.log('客户端返回是否可以制作的参数不正确, arr[4]: ' + arr[4] + ', _id: ' + _id); break;
                }
            })
        })
    }

    //下发出餐
    outFood(key, order) {
        const { _id, orderDetail, _outFoodOrderId, position } = order
        let { freezerStatus, thermotank1Status, thermotank2Status, inport1Status, inport2Status, outport1Status, outport2Status } = fnGetDeviceStatusObj(this.devices['170'])
        if (position === 1 && !thermotank1Status) return console.log('1号保温柜忙碌中, 不能出餐')
        if (position === 2 && !thermotank2Status) return console.log('2号保温柜忙碌中, 不能出餐')

        let content = this.messageResponse(170, 6, this.random, 6, _outFoodOrderId, orderDetail.thermotankNo, orderDetail.placeNo)
        console.log('下发出餐', content, date.format(new Date(), 'YYYY-MM-DDThh:mm:ss'))
        this.send(this.clients[key], content, (key1, arr, type) => {
            arr[4] === 4 ? 0 : arr[4]
            if (arr[4] === 4) { //无餐
                arr[4] = 0
                console.log('出餐的格子无餐, 请人工处理, _id' + _id)
            }
            HotpotOutFoodOrder.updateOne({ _id }, { status: arr[4] }, async (error, result1) => {
                if (error) return
                switch (arr[4]) {
                    case 1: console.log('更新成功, _id: ' + _id); break;
                    case 2: console.log('执行失败，正在出餐中或者保温柜无库存, _id: ' + _id); break;
                    case 3: console.log('出餐忙碌中，稍后重试, _id: ' + _id); break;
                    case 4: console.log('出餐的格子无餐, _id: ' + _id); break;
                    default: console.log('出餐已更新,但客户端返回是否可以制作的参数不正确, arr[4]: ' + arr[4] + ', _id: ' + _id); break;
                }
                console.log(order.type, arr[4])
                if (order.type === 0 && arr[4] !== 1) {
                    //失败上报更新菜品状态
                    console.log({ storeId: this.storeId, deviceId: this.deviceId, orderDetailId: order.orderDetailId, thermotankNo: orderDetail.thermotankNo, placeNo: orderDetail.placeNo, productStatus: 999 })
                    let [err1, res1] = await to(requpdateProductStatus({ storeId: this.storeId, deviceId: this.deviceId, orderDetailId: order.orderDetailId, thermotankNo: orderDetail.thermotankNo, placeNo: orderDetail.placeNo, productStatus: 999, access_token: this.access_token }))
                    console.log(err1, res1)
                    if (err1) return
                    if (res1.statusCode !== '200') return console.log(res1.statusMsg)
                    console.log('更新出餐菜品状态到云端成功,状态为出餐失败,_outFoodOrderId=' + arr[4], arr.toString())
                }
            })
        })
    }

    //下发放餐
    async inFood(key, inportId) {
        if(this.forceLock) return console.log('强制停止状态中,无法放餐')
        // console.log(key, inportId)
        //调接口获取放餐位置数据
        // console.log({ storeId: this.storeId, deviceId: this.deviceId, productId: inportId == 1 ? this.productId1 : this.productId2 })
        let [err, res] = await to(reqgetThermotankGivePlace({ storeId: this.storeId, deviceId: this.deviceId, productId: inportId == 1 ? this.productId1 : this.productId2, access_token: this.access_token }))
        console.log(err, res)
        if (err) return
        if (res.statusCode !== '200') return console.log(res.statusMsg)

        let orderDetail = res.data

        let insertData = [{
            date: today,
            orderDetail,
            position: inportId,
            status: 0
        }]

        //发送放餐命令前先存入数据库
        let [error1, result1] = await to(HotpotInFoodOrder.insertMany(insertData))
        if (error1) return console.log(error1)

        let { _id, _inFoodOrderId } = result1[0]
        let content = this.messageResponse(170, 8, this.random, 6, _inFoodOrderId, orderDetail.thermotankNo, orderDetail.placeNo)
        console.log('下发放餐', content, date.format(new Date(), 'YYYY-MM-DDThh:mm:ss'))
        //发送放餐
        this.send(this.clients[key], content, async (key, arr, type) => {
            HotpotOutFoodOrder.updateOne({ _id }, { status: arr[4] }, (error2, result2) => {
                if (error2) return
                switch (arr[4]) {
                    case 1: console.log('放餐更新成功, _id: ' + _id); break;
                    case 2: console.log('放餐执行失败, _id: ' + _id); break;
                    case 3: console.log('放餐忙碌中，稍后重试, _id: ' + _id); break;
                    case 4: console.log('放餐格子已有餐, _id: ' + _id); break;
                    default: console.log('放餐已更新,但客户端返回是否可以制作的参数不正确, arr[4]: ' + arr[4] + ', _id: ' + _id); break;
                }
            })
        })
    }

    //下发预热炉头
    preFurnace(key, order) {
        const { _id, _preFurnaceOrderId, furnaceId, quantity } = order
        let content = this.messageResponse(170, 11, this.random, 6, _preFurnaceOrderId, furnaceId, quantity)
        console.log('下发预热炉头', content, date.format(new Date(), 'YYYY-MM-DDThh:mm:ss'))
        this.send(this.clients[key], content, (key1, arr, type) => {
            HotpotPreFurnaceOrder.updateOne({ _id }, { status: arr[4] }, (error, result1) => {
                if (error) return
                switch (arr[4]) {
                    case 1: console.log('更新成功, _id: ' + _id); break;
                    case 2: console.log('执行失败, _id: ' + _id); break;
                    case 3: console.log('预热炉头忙碌中，稍后重试, _id: ' + _id); break;
                    default: console.log('预热炉头已更新,但客户端返回是否可以制作的参数不正确, arr[4]: ' + arr[4] + ', _id: ' + _id); break;
                }
            })
        })
    }

    issueOrders(key, deviceStatus) {
        let { freezerStatus, thermotank1Status, thermotank2Status, inport1Status, inport2Status, outport1Status, outport2Status } = fnGetDeviceStatusObj(deviceStatus)
        //冷库正常/获取备餐数据

        if (freezerStatus && !this.freezerLock) {
            this.prepareSort = this.prepareSort * -1
            HotpotOrder.find({ $and: [{ $or: [{ status: 0 }, { status: 3 }] }, { date: today },] }).then(res => {

                if (!res[0]) return //console.log('当前没有备餐任务')
                if (this.prepareSort === 1) {
                    this.prepareFood(key, res[0])
                } else {
                    this.prepareFood(key, res[res.length - 1])
                }

            }).catch(err => {
                console.log(err)
                console.log('获取备餐数据有误11')
            })
        }

        setTimeout(() => {
            //执行放餐1
            if (inport1Status && thermotank1Status) {
                this.inFood(key, 1)
            }
        }, 1000)
        setTimeout(() => {
            //执行放餐2
            if (inport2Status && thermotank2Status) {
                this.inFood(key, 2)
            }
        }, 2000)


    }

    //心跳
    command1(socket, arr) {
        this.devices[arr[0]] = fnGetNewDevicesStatus(arr)
        socket.send(this.responseMsg(arr))
    }

    //异常上报
    command2(socket, arr) {
        this.devices[arr[0]] = fnGetNewDevicesStatus(arr)
        socket.send(this.responseMsg(arr))
    }

    //状态上报
    command3(socket, arr) {
        this.devices[arr[0]] = fnGetNewDevicesStatus(arr)
        HotpotDeviceStatus.updateOne({ head: arr[0] + '' }, { detail: this.devices[arr[0]] }, (error, result) => {
            if (error) console.log('状态上报更新数据库有误')
            if (!result) console.log('状态上报更新数据库失败')
        })
        socket.send(this.responseMsg(arr))
        let machine = this.machineInfos.find(item => item.header === arr[0] + '')
        //解析设备状态\下发命令
        // this.issueOrders(machine.ip, this.devices[arr[0]])
    }

    //从数据库中获取设备状态
    getDeviceStatus(isSend) {

        HotpotDeviceStatus.findOne({ head: '170' }, (error, result) => {
            if (error) return console.log('初始化状态失败')
            if (result) this.devices['170'] = result.detail
            if (isSend) {
                // console.log(isSend)
                let machine = this.machineInfos.find(item => item.header === '170')
                //解析设备状态\下发命令
                this.issueOrders(machine.ip, this.devices['170'])
            }
        })
    }

    //备餐完成
    async command5(socket, arr) {
        // 任务号 arr[4]
        let [error, result] = await to(HotpotOrder.findOne({ date: today, _mealId: arr[4] }))
        if (error) return
        if (!result) return console.log('客户端发送的备餐任务号不存在arr[4]=' + arr[4], arr)
        if (result.status !== 1) return console.log('该订单号的状态为status=' + result.status, '不能处理')
        let [error1, result1] = await to(HotpotOrder.updateOne({ date: today, _mealId: arr[4] }, { status: 5 }))
        if (error1) return
        console.log('更新备餐任务成功,_mealId=' + arr[4], arr.toString())
        socket.send(this.responseMsg(arr))

        let [err, res] = await to(reqchangeFreezerStock({ storeId: this.storeId, deviceId: this.deviceId, deviceLevel: result.orderDetail.deviceLevel, quantity: -1, access_token: this.access_token }))
        console.log(err, res)
        if (err) return

        let [error2, result2] = await to(HotpotOrder.updateOne({ date: today, _mealId: arr[4] }, { status: 5 }))
        if (error2) return

        console.log('上报备餐后减少冷库库存成功,_mealId=' + arr[4], arr.toString())
    }

    //出餐完成
    async command7(socket, arr) {
        // 任务号 arr[4]
        let [error, result] = await to(HotpotOutFoodOrder.findOne({ date: today, _outFoodOrderId: arr[4] }))
        if (error) return
        if (!result) return console.log('客户端发送的出餐任务号不存在arr[4]=' + arr[4], arr.toString())
        let [error1, result1] = await to(HotpotOutFoodOrder.updateOne({ date: today, _outFoodOrderId: arr[4] }, { status: 5 }))
        if (error1) return
        console.log('更新出餐任务成功,_outFoodOrderId=' + arr[4], arr.toString())
        socket.send(this.responseMsg(arr))

        let [err, res] = await to(reqchangeThermotankStock({ storeId: this.storeId, deviceId: this.deviceId, thermotankNo: result.orderDetail.thermotankNo, placeNo: result.orderDetail.placeNo, placeStock: 0, access_token: this.access_token }))
        console.log(err, res)
        if (err) return
        let [error2, result2] = await to(HotpotOutFoodOrder.updateOne({ date: today, _outFoodOrderId: arr[4] }, { status: 6 }))
        if (error2) return
        console.log('更新出餐任务发送到云端成功,_outFoodOrderId=' + arr[4], arr.toString())
        if (result.type === 0) {
            //成功上报更新菜品状态
            console.log({ storeId: this.storeId, deviceId: this.deviceId, orderDetailId: result.orderDetailId, thermotankNo: result.orderDetail.thermotankNo, placeNo: result.orderDetail.placeNo, productStatus: 317 })
            let [err1, res1] = await to(requpdateProductStatus({ storeId: this.storeId, deviceId: this.deviceId, orderDetailId: result.orderDetailId, thermotankNo: result.orderDetail.thermotankNo, placeNo: result.orderDetail.placeNo, productStatus: 317, access_token: this.access_token }))
            console.log(err1, res1)
            if (err1) return
            if (res1.statusCode !== '200') return console.log(res.statusMsg)
            console.log('更新出餐菜品状态到云端成功,_outFoodOrderId=' + arr[4], arr.toString())
        }
    }

    //放餐完成
    async command9(socket, arr) {
        // 任务号 arr[4]
        let [error, result] = await to(HotpotInFoodOrder.findOne({ date: today, _inFoodOrderId: arr[4] }))
        if (error) return
        if (!result) return console.log('客户端发送的放餐任务号不存在arr[4]=' + arr[4], arr.toString())
        let [error1, result1] = await to(HotpotInFoodOrder.updateOne({ date: today, _inFoodOrderId: arr[4] }, { status: 5 }))
        if (error1) return
        console.log('更新放餐任务成功,_inFoodOrderId=' + arr[4], arr.toString())
        socket.send(this.responseMsg(arr))

        let [err, res] = await to(reqchangeThermotankStock({ storeId: this.storeId, deviceId: this.deviceId, thermotankNo: result.orderDetail.thermotankNo, placeNo: result.orderDetail.placeNo, placeStock: 1, access_token: this.access_token }))
        console.log(err, res)
        if (err) return
        let [error2, result2] = await to(HotpotInFoodOrder.updateOne({ date: today, _inFoodOrderId: arr[4] }, { status: 6 }))
        if (error2) return
        console.log('更新放餐任务发送到云端成功,_inFoodOrderId=' + arr[4], arr.toString())

    }
    //炉头状态上报
    command10(socket, arr) {
        this.furnace1[arr[0]] = fnGetFurnaceStatus(arr[5], arr[6])
        this.furnace2[arr[0]] = fnGetFurnaceStatus(arr[8], arr[9])
        socket.send(this.responseMsg(arr))
    }

    //定时获取预热炉头命令
    getFurnaceOrder() {
        let machine = this.machineInfos.find(item => item.header === '170')
        if (!machine) return console.log('设备未连接')
        HotpotPreFurnaceOrder.findOne({ date: today, status: 0, furnaceId: 1 }).then(res => {
            if (!res) return //console.log('当前没有预热任务1')
            this.preFurnace(machine.ip, res)
        }).catch(err => {
            console.log(err)
        })
        setTimeout(() => {
            HotpotPreFurnaceOrder.findOne({ date: today, status: 0, furnaceId: 2 }).then(res => {
                if (!res) return //console.log('当前没有预热任务2')
                this.preFurnace(machine.ip, res)
            }).catch(err => {
                console.log(err)
            })
        }, 1000)
    }

    //预热炉头完成
    async command12(socket, arr) {
        // 任务号 arr[4]
        let [error, result] = await to(HotpotPreFurnaceOrder.findOne({ date: today, _preFurnaceOrderId: arr[4] }))
        if (error) return
        if (!result) return console.log('客户端发送的预热炉头任务号不存在arr[4]=' + arr[4], arr.toString())
        let [error1, result1] = await to(HotpotPreFurnaceOrder.updateOne({ date: today, _preFurnaceOrderId: arr[4] }, { status: 4 }))
        if (error1) return
        console.log('更新预热炉头任务成功,_preFurnaceOrderId=' + arr[4], arr.toString())
        socket.send(this.responseMsg(arr))
    }

}
module.exports = hotPotRice;